package com.github.m6d21.sso.support.validator.password;

import com.github.m6d21.sso.support.validator.password.PasswordConstant.Type;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *<p>
 *密码验证器
 *</p>
 *
 * @author liuyang
 * @date 2018-12-06 Thu 16:52:43
 * @since 1.0.0
 */
public class PasswordValidator implements ConstraintValidator<Password, String> {

    private static final Logger LOG = LoggerFactory.getLogger(PasswordValidator.class);

    private Type type;

    @Override
    public void initialize(Password password) {
        this.type = password.type();
    }

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        if (password == null || password.length() == 0) {
            return true;
        }
        if (type == null) {
            type = Type.SIMPLE;
        }
        Pattern pattern = Pattern.compile(type.getRegexp());
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }
}
